package com.mercury.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class WeChat {

    private static String wxAppid = "wxcf6fe3913ff1cf68";

    private static String wxAppsecret = "6f7154f0a1adc10e655fe2af4d204ee0";

    private static String wxMechid = "1500553471";

    private static String key = "YyY12344321YyY12344321YyY1234432";

    static WxPayData payResult = new WxPayData();

    public static String getAccessToken() {
        String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppid + "&secret=" + wxAppsecret + "";
        String accessToken = "";
        String respText = "";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(getAccessTokenUrl);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            respText = EntityUtils.toString(response.getEntity());
            JSONObject object = JSON.parseObject(respText);
            if (!object.containsKey("access_token")) {
                return respText;
            }
            accessToken = object.getString("access_token");
        } catch (IOException e) {
            e.printStackTrace();
            return accessToken;
        }
        return accessToken;
    }

    public static String getTicKet(String token) {
        String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
        String ticket = "";
        String respText = "";
        if (!token.equals("")) {
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(getAccessTokenUrl);
            try {
                HttpResponse response = httpClient.execute(httpGet);
                respText = EntityUtils.toString(response.getEntity());
                JSONObject object = JSON.parseObject(respText);
                if (!object.containsKey("ticket")) {
                    return respText;
                }
                ticket = object.getString("ticket");
            } catch (IOException e) {
                e.printStackTrace();
                return ticket;
            }
        }
        return ticket;
    }

    public static String CheckSignature(String ticket, long timestamp, String urlvue) {
        String jsapi_ticket = "jsapi_ticket=" + ticket + "&noncestr=wego&timestamp=" + timestamp + "&url=" + urlvue;
        String signature = DigestUtils.sha1Hex(jsapi_ticket);
        return signature.toLowerCase();
    }

    /**
     * 获取当前时间的时间戳
     *
     * @return 当前unix时间戳
     */
    public static long CreatenTimestamp() {
        return new Date().getTime();
    }

    /**
     * 获取OPENID
     *
     * @param code
     * @return
     */
    public static String GetOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxAppid + "&secret=" + wxAppsecret + "&code=" + code + "&grant_type=authorization_code";
        String respText;
        String OpenId = "";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            respText = EntityUtils.toString(response.getEntity());
            JSONObject object = JSON.parseObject(respText);
            System.out.println("GetOpenId json ===>" + object);
            OpenId = object.getString("openid");
        } catch (IOException e) {
            e.printStackTrace();
            return OpenId;
        }
        return OpenId;
    }

    public static String Getoauth(HttpServletRequest request) {
        String url = request.getParameter("url");
        String state = request.getParameter("state");
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxAppid +
                "&redirect_uri=" + url +
                "&response_type=code&scope=snsapi_base&state=" + state +
                "#wechat_redirect";
    }

    public static boolean QueryOrder(String transaction_id) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("xml");
        root.addElement("appid").addText(wxAppid);
        root.addElement("mch_id").addText("1500553471");
        root.addElement("nonce_str").addText(UUID.randomUUID().toString().replace("-", ""));
        root.addElement("transaction_id").addText(transaction_id);
        String signText = "appid=" + wxAppid + "&mch_id=1500553471&nonce_str=" + root.element("nonce_str").getText() + "&transaction_id=" + transaction_id + "&key=" + key;
        try {
            String sign = DigestUtils.md5Hex(signText).toUpperCase();
            root.addElement("sign").addText(sign);
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
            HttpEntity entity = new StringEntity(document.asXML());
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            Document resultXml = DocumentHelper.parseText(result);
            Element resultRoot = resultXml.getRootElement();
            return resultRoot.element("return_code").getText().equals("SUCCESS") && resultRoot.element("result_code").getText().equals("SUCCESS");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static JSONObject GetUnifiedOrderResult(String strBody, String strAttach, String openid, String totalFee) {
        Date date = new Date();

        WxPayData data = new WxPayData();
        data.setValue("appid", wxAppid);
        data.setValue("mch_id", wxMechid);
        data.setValue("spbill_create_ip", "47.98.51.31");
        data.setValue("notify_url", "http://wx.yilaibaobei.com:6600/api/invoke/WxResultNotify");
        data.setValue("nonce_str", UUID.randomUUID().toString().replace("-", ""));
        data.setValue("body", strBody);
        data.setValue("attach", strAttach);
        data.setValue("out_trade_no", wxMechid + new SimpleDateFormat("yyyyMMddHHmmss").format(date) + new Random().nextInt(999));
        data.setValue("total_fee", Integer.valueOf(totalFee));
        data.setValue("trade_type", "JSAPI");
        data.setValue("openid", openid);
        data.setValue("sign", data.makeSign());

        String xml = data.toXml();
        System.out.println("data："+xml);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");

        post.addHeader("Content-Type", "text/xml");
        post.addHeader("charset","utf-8");

        try {
            HttpEntity entity = new StringEntity(xml,"text/xml", "utf-8");
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");

            System.out.println("微信下单接口结果：" + result);

            Document resultXml = DocumentHelper.parseText(result);
            payResult.fromXml(resultXml);
            Element resultRoot = resultXml.getRootElement();

            WxPayData jsApiParam = new WxPayData();
            jsApiParam.setValue("appId", wxAppid);
            jsApiParam.setValue("timeStamp", String.valueOf(new Date().getTime()));
            jsApiParam.setValue("nonceStr", resultRoot.element("nonce_str").getText());
            jsApiParam.setValue("package", "prepay_id=" + resultRoot.element("prepay_id").getText());
            jsApiParam.setValue("signType", "MD5");
            jsApiParam.setValue("paySign", jsApiParam.makeSign());

            System.out.println("二次签名数据：" + jsApiParam);

            JSONObject json = new JSONObject();

            json.put("appId", wxAppid);
            json.put("timeStamp", jsApiParam.getValue("timeStamp"));
            json.put("packageValue", jsApiParam.getValue("package"));
            json.put("nonceStr", jsApiParam.getValue("nonceStr"));
            json.put("paySign",jsApiParam.getValue("paySign"));
            json.put("msg", "正在接入微信支付");

            System.out.println("拉起Bridge数据：" + json);

            return json;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
